import React from 'react';
import {connect} from 'dva';
import {
	Button,
	Row,
	Col,
	Tabs,
	Upload,
	Icon,
	InputNumber,
	message,
	Checkbox
} from 'antd';
import {routerRedux} from 'dva/router';
import reqwest from 'reqwest';
import {fetchGet} from '../../../utils/utils';
import styles from './style.less';
import config from '../../../config';
import host from '../../../services/host';

const TabPane = Tabs.TabPane;

class Step3 extends React.Component {
	constructor(state) {
		super(state);
		const {data} = this.props;

		const patt = /<img[^>]+src=['"]([^'"]+)['"]+/g;
		const articleImgs = [];
		let temp;

		while ((temp = patt.exec(data.content)) != null) {
			articleImgs.push(this.escape2Html(temp[1]));
		}
		this.filterImg(articleImgs);
	}
	state = {
		imgUrl: [],
		upload_access_token: [],
		loading: false,
		cover: '',
		coverList: [],
		seq:0,
		recommendCoverList: [],
		recommend_cover: '',
		recommend: false,
		needConfirmImages: []
	};

	componentDidMount() {
		const {data, dispatch} = this.props;
		if (data.cover) {
			this.setState({
				coverList: [
					{
						uid: -1,
						name: '推荐封面图',
						status: 'done',
						url: data.cover
					}
				]
			});
		}
		if (data.recommend_cover) {
			this.setState({
				recommendCoverList: [
					{
						uid: -1,
						name: '推荐封面图',
						status: 'done',
						url: data.recommend_cover
					}
				]
			});
		}
		this.setState({
			recommend: data.recommend,
			seq : data.seq
		});
		dispatch({type: 'upload/fetchAccessToken'});
	};

	onloadImg(img) {
		const my = this;
		return function() {
			if (img.width > 100 && img.height > 100) {
				my.state.imgUrl.push(img.src);
				my.setState({imgUrl: my.state.imgUrl});
			}
		};
	}
	filterImg(imgUrl) {
		for (let i = 0; i < imgUrl.length; i++) {
			const img = new Image();
			img.src = imgUrl[i];
			img.onload = this.onloadImg(img);
		}
	}
	escape2Html(str) {
		const arrEntities = {
			lt: '<',
			gt: '>',
			nbsp: ' ',
			amp: '&',
			quot: '"'
		};
		return str.replace(/&(lt|gt|nbsp|amp|quot);/gi, function(all, t) {
			return arrEntities[t];
		});
	}

	settingCover() {
		const {data, uploadAccessToken, dispatch, getUploadAccessTokenStatus} = this.props;
		const handleRemove = file => {
			console.log(file);
			this.setState(({coverList}) => {
				const index = coverList.indexOf(file);
				const newFileList = coverList.slice();
				newFileList.splice(index, 1);
				return {coverList: newFileList, cover: ''};
			});
		};

		const handleChange = ({fileList}) => {
			this.setState({coverList: fileList});
			if (fileList[0].status === 'done') {
				if (fileList[0].response.code === 0) {
					const url = fileList[0].response.data.files.file.url;
					this.setState(({needConfirmImages}) => {
						const newNeedConfirmImages = needConfirmImages;
						newNeedConfirmImages.push({url: url, upload_access_token: uploadAccessToken});
						return {cover: url, needConfirmImages: newNeedConfirmImages};
					});

					//　重新获取上传的accessToken
					dispatch({type: 'upload/fetchAccessToken'});
				}
			}
		}

		const props = {
			name: 'file',
			action: config.upload_server_url,
			data: {
				accessToken: uploadAccessToken
			},
			multiple: false,
			listType: 'picture-card',
			fileList: this.state.coverList,
			onRemove: handleRemove,
			onChange: handleChange
		};

		return (<Row type='flex' justify='center'>
			<Upload {...props}>
				{
					this.state.coverList.length >= 1
						? null
						: (<div>
							<Icon type={this.state.loading
									? 'loading'
									: 'plus'}/>
							<div className="ant-upload-text">上传封面图</div>
						</div>)
				}
			</Upload>
		</Row>);
	};

	settingRecommendCover() {
		const {data, uploadAccessToken, url, dispatch, getUploadAccessTokenStatus} = this.props;
		const handleRemove = file => {
			this.setState(({recommendCoverList}) => {
				const index = recommendCoverList.indexOf(file);
				const newFileList = recommendCoverList.slice();
				newFileList.splice(index, 1);
				return {recommendCoverList: newFileList, recommend_cover: ''};
			});
		};

		const handleChange = ({fileList}) => {
			this.setState({recommendCoverList: fileList});
			if (fileList[0].status === 'done') {
				if (fileList[0].response.code === 0) {
					const url = fileList[0].response.data.files.file.url;
					this.setState(({needConfirmImages}) => {
						const newNeedConfirmImages = needConfirmImages;
						newNeedConfirmImages.push({url: url, upload_access_token: uploadAccessToken});
						return {recommend_cover: url, needConfirmImages: newNeedConfirmImages};
					});

					//　重新获取上传的accessToken
					dispatch({type: 'upload/fetchAccessToken'});
				}
			}
		}

		const handleRecommend = e => {
			this.setState({
				recommend: e.target.checked
					? 1
					: 0
			});
		};

		const props = {
			name: 'file',
			action: config.upload_server_url,
			data: {
				accessToken: uploadAccessToken
			},
			multiple: false,
			listType: 'picture-card',
			fileList: this.state.recommendCoverList,
			onRemove: handleRemove,
			onChange: handleChange
		};

		return (<div>
			<Row type='flex' justify='center'>
				<Upload {...props}>
					{
						this.state.recommendCoverList.length >= 1
							? null
							: (<div>
								<Icon type={this.state.loading
										? 'loading'
										: 'plus'}/>
								<div className="ant-upload-text">上传推荐展示的封面图</div>
							</div>)
					}
				</Upload>
			</Row>
		</div>);
	};

	settingSeq() {
		const setSeq = (val) => {
			console.log(val);
			this.setState({
				seq : val
			});
		}
		return (<div>
			<Row type='flex' >
				<InputNumber onChange={setSeq} ref='seq' placeholder="排序" defaultValue={this.state.seq}/>
			</Row>
		</div>)
	};

	render() {
		const {data, dispatch} = this.props;
		const onPrev = () => {
			this.props.dispatch(routerRedux.push(`/article/pub-article/content?id=${data.id}`));
		};
		const onValidateForm = e => {
			e.preventDefault();
			dispatch({
				type: 'article/submitStepForm',
				payload: {
					...data,
					...this.state
				}
			});
		};

		return (<div>
			<Tabs defaultActiveKey="1">
				<TabPane tab="设置封面小图" key="1">
					{this.settingCover()}
				</TabPane>
				<TabPane tab="设置封面大图" key="2">
					{this.settingRecommendCover()}
				</TabPane>
				<TabPane tab="设置顺序" key="3">
					{this.settingSeq()}
				</TabPane>
			</Tabs>
			<Row type="flex" justify="center" style={{
					marginTop: '40px'
				}}>
				<Button onClick={onPrev} style={{
						marginRight: 8
					}}>
					上一步
				</Button>
				<Button type="primary" onClick={onValidateForm}>
					完成
				</Button>
			</Row>
		</div>);
	}
}

export default connect(({article, upload, loading}) => ({data: article.step, uploadAccessToken: upload.access_token, url: upload.url, getUploadAccessTokenStatus: loading.effects['upload/fetchAccessToken']}))(Step3);
